package com.charwayh.mvcframework.servlet;

import com.charwayh.mvcframework.annotation.CwController;
import com.charwayh.mvcframework.annotation.CwService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author charwayH
 * 前端控制器
 * 扫描项目中的spring.xml配置文件
 */
public class CwDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();
    /**
     * 缓存加载到类的全限定类名
      */
    private List<String> classNames = new ArrayList<>();

    //ioc容器
    private Map<String,Object> ioc = new HashMap<String,Object>();


    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1.加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2.扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        // 3.初始化bean对象(实现ioc容器，基于注解)
        doInstance();
        // 4.实现依赖注入
        doAutoWired();
        // 5.构造一个HandleMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

        System.out.println("Cw MVC初始化完成");
        // 等待请求进入，处理请求

    }


    /**
     * 构造一个HandlerMapping处理器映射器
     */
    private void initHandlerMapping() {

    }

    /**
     * 实现依赖注入
     */
    private void doAutoWired() {

    }

    /**
     * ioc容器
     * 基于classNames缓存类的全限定类名，以及反射技术完成对象创建和管理
     */
    private void doInstance() {
        if(classNames.size() == 0){ return;}

        for (int i = 0; i < classNames.size(); i++) {
            // com.charwayh.demo.controller.DemoController
            String className = classNames.get(i);

            try {
                // 反射
                Class<?> aClass = Class.forName(className);
                // 区分controller和service
                if(aClass.isAnnotationPresent(CwController.class)){
                    // controller的id此处就不做过多的处理，不取value了，就拿类的首字母小写作为id保存到ioc容器中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstsimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstsimpleName, o);
                }else if(aClass.isAnnotationPresent(CwService.class)){
                    CwService annotation = aClass.getAnnotation(CwService.class);
                    // 获取注解value值
                    String beanName = annotation.value();
                    // 如果指定了id，就以指定的为准
                    if (!"".equals(beanName.trim())){
                        ioc.put(beanName,aClass.newInstance());
                    }else{
                        //如果没有指定，就以类名首字母小写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }

                    // service层往往是有接口的，面向接口开发的，此时再以接口名为id，放入一份对象到ioc容器中，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以借口的全限定名作为id放入
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }
                }


            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 扫描类
     */
    private void doScan(String scanPackage) {
        // 需要通过包名找到磁盘上的路径，通过路径去判断该包下是否存在子包(递归)
        String sacnPackagePath = (Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage).replace("\\.", "/");
        File pack = new File(sacnPackagePath);

        File[] files = pack.listFiles();

        for (File file : files) {
            if(file.isDirectory()){
                doScan(scanPackage + "." + file.getName());
            }else if (file.getName().endsWith(".class")){
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收处理请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 调用doPost
        doPost(req, resp);
    }

    // 真正处理请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    
    // 首字母小写
    public String lowerFirst(String str){
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <='Z'){
            chars[0] +=32;
        }
        return String.valueOf(chars);
    }
}
